package com.fm.magic.net.chrome;

import com.fm.magic.net.chrome.domain.Page;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;

import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author leo.li
 */
public class ChromeTab {
    private WebSocket webSocket;
    private SocketInfo info;
    private AtomicInteger integer = new AtomicInteger();

    public ChromeTab(WebSocketFactory webSocketFactory, SocketInfo info) throws IOException {
        this.webSocket = prepareWebSocket(webSocketFactory, info);
        this.info = info;
    }

    public WebSocket prepareWebSocket(WebSocketFactory webSocketFactory, SocketInfo info) throws IOException {
        WebSocket socket = webSocketFactory.createSocket(info.getWebSocketDebuggerUrl());
        socket.addListener(new ChromeWebSocketListener());
        try {
            socket.connect();
        } catch (WebSocketException e) {
            throw new RuntimeException(e);
        }
        socket.setAutoFlush(true);
        return socket;
    }

    public Page getPage() {
        return new Page(this);
    }

    public WebSocket getWebSocket() {
        return webSocket;
    }

    public int getNextRequestId() {
        return integer.incrementAndGet();
    }
}
